#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2019-01-28 16:19:44
from base_server.sqlop import *

from flask import Flask, jsonify, Response, make_response
# from sqlalchemy import null
from apps.monitor.views import *
from datetime import timedelta
from apps.route_demo.views import *
from apps.ci.views import *
from apps.resources.views import *
from apps.quality.views import *
from apps.test_tools.views import *

app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)  # 设置为24位的字符,每次运行服务器都是不同的，所以服务器启动一次上次的session就清除。
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)  # 设置session的保存时间。
app.config['SESSION_COOKIE_NAME'] = 'login_auth'

app.config.from_object('settings.DevConfig')

play = playMethods()
sp = serverPPTX()

'''
这里是注册蓝图
参数url_prefix='/xxx'的意思是设置request.url中的url前缀，
即当request.url是以/monitor的情况下才会通过注册的蓝图的视图方法处理请求并返回
'''
app.register_blueprint(monitor, url_prefix='/monitor')
app.register_blueprint(route_demo, url_prefix='/route_demo')
app.register_blueprint(route_demo, url_prefix='/route_zll')
app.register_blueprint(ci, url_prefix='/ci')
app.register_blueprint(resources, url_prefix='/resources')
app.register_blueprint(quality, url_prefix='/quality')
app.register_blueprint(test_tools, url_prefix='/test_tools')


# 判断登录装饰器方法
def check_token(func):
    @wraps(func)
    def inner(*args, **kwargs):
        conf = configparser.ConfigParser()
        conf.read("conf/config.ini")
        token_key = conf.get('token', 'key')
        token = request.cookies.get('token')
        if token == token_key:
            return func(*args, **kwargs)
        else:
            data = json.dumps({"code": 1001})
            return data

    return inner


@app.route('/', methods=['get'])
@app.route('/index', methods=['get'])
# @check_permissions('/index')
def index():
    return render_template('index.html')


# 获取菜单目录
@app.route('/menu', methods=['GET', 'POST'])
def menu():
    try:
        leven = session.get('username')[1]
    except:
        leven = 0
    menu = get_menu(leven)
    ret = {"code": 1000, "menu": menu}
    return json.dumps(ret)
    # return render_template('base.html', menu=menu)


# 2.登录
@app.route('/login_new', methods=['GET', 'POST'])
def login_new():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        login = Login(username, password)
        data = login.valid_login()
        if data:
            session["username"] = data
            ret = {"Status": "ok", "Text": "登陆成功"}
            resp = Response(json.dumps(ret))
            resp.set_cookie('username', data[0])
            return resp
        else:
            ret = {"Status": "Erro", "Erro": "用户名密码不匹配"}
            return json.dumps(ret)
    else:
        if session.get('username'):
            return redirect('index')
        return render_template('login.html')


# 退出
@app.route('/logout', methods=['GET', 'POST'])
def logout():
    data = session.get('username')
    if data is None:
        ret = make_response(redirect('login_new'))
        ret.delete_cookie('username')  # 清除cookies:username
    else:
        session.pop('username')  # 清除session
        ret = make_response(redirect('login_new'))
        ret.delete_cookie('username')  # 清除cookies:username
    return ret


# 微信小工具首页
@app.route('/wxtools', methods=['get', 'post'])

def wxtools():
    if request.method == "GET":
        global login_status
        if login_status == 0:
            itinit()
        return render_template('wxtools.html')


# 查询登录状态
@app.route('/status', methods=['get', 'post'])
def status():
    data = lc_status()
    return json.dumps(data)


# 登录
@app.route('/login', methods=['post'])
def login():
    ret = lc()
    if ret == 1:
        data = {"code": 1000}
        return json.dumps(data)
    else:
        data = {"code": 1001}
        return json.dumps(data)


# 退出登录
@app.route('/exit', methods=['post'])
def exit():
    ec()
    return 'ok'


# 统计接口
@app.route('/statistic', methods=['post'])
def statistic():
    sex = statistic_friends_sex()
    Province = statistic_friends_city()
    nickname = get_nickname()
    wc1 = wc()
    if sex == "nologin" or Province == "nologin" or nickname == "nologin" or wc1 == "nologin":
        global login_status
        login_status = 0
        data = {"code": 1001}
        return json.dumps(data)
    else:
        data = {"code": 1000, "sex": sex, "Province": Province}
        return json.dumps(data)


@app.route('/time_test', methods=['post', 'get'])
# @check_permissions("/time_test")
def time_test():
    if request.args.get('url'):
        url = request.args.get('url')
    else:
        url = 'http://127.0.0.1:5000/time_test_hello'
    return render_template('time_test.html', url=url)


# 响应时间测试
@app.route('/time_test_rt', methods=['post', 'get'])
def time_test_rt():
    retest = Time_Test()
    res = retest.response_time(json.loads(request.get_data().decode("utf-8"))['url'])
    return json.dumps(res)


# 响应时间测试加载页
@app.route('/time_test_hello', methods=['post', 'get'])
def time_test_hello():
    return render_template('hello.html')


# 验证token
@app.route('/token_check', methods=['post', 'get'])
def token_check():
    if request.method == 'POST':
        global token
        token = request.get_data()

        if token == b'':
            token = request.cookies.get('token')
        else:
            token = json.loads(token.decode("utf-8"))
            token = str(token['token'])
        data = token_check1(token)
        return json.dumps(data)
    else:
        return render_template('admin.html')


# @app.route('/test2',methods=['post','get'])
# def test1():
# 	return render_template('test.html')


@app.route('/test1', methods=['post', 'get'])
def test2():
    data = {"code": 1000, "sex": 1, "Province": 1}
    return json.dumps(data)


# admin页面
@app.route('/admin', methods=['get', 'post'])
def admin():
    return render_template('admin.html')



@app.route('/test', methods=['post', 'get'])
def test():
    # data = {"code":1000,"sex": '1', "Province": '44231'}
    return render_template('index_test.html')


# flask动态路由测试
@app.route('/1/<url>', methods=['post', 'get'])
def test_1(url):
    data = "1/%s.html" % url
    return render_template(data)



# # 抓虫节排行榜
# @app.route('/grab_bug', methods=['post', 'get'])
# # @check_permissions("/grab_bug")
# def grab_bug():
#     grab = Grab_Bug()
#     data = grab.get_bug_score()
#     return render_template('grab_bug.html', data=data)


# yapi页
@app.route('/yapi', methods=['get'])
# @check_permissions("/yapi")
def yapi():
    return render_template('yapi.html')


@app.route('/download', methods=['get'])
def download():
    import os
    if request.method == "GET":
        # if os.path.isfile("C:/Users/zhoujian/Desktop/3.0_0.crx"):
        # return send_from_directory("C:/Users/zhoujian/Desktop","3.0_0.crx",as_attachment=True)
        if os.path.isfile("/home/YApi/3.0_0.crx"):
            return send_from_directory("/home/YApi/", "3.0_0.crx", as_attachment=True)
        abort(404)







# 以下为周报路由
@app.route('/weekly', methods=['post', 'get'])
def weekly():
    return app.send_static_file('html/weekly.html')


@app.route('/weekly_index', methods=['post', 'get'])
# @check_permissions("/time_test")
def weekly_index():
    return render_template('weekly_index.html')


# 提交后就生成单独组的周报
@app.route('/subWeekly', methods=['post', 'get'])
def subWeekly():
    if request.method == 'POST':
        weekly = request.get_data()
        weekly = json.loads(weekly.decode("utf-8"))
        group_id = weekly['group']
        weekly = str(weekly).replace("\'", "\\'")
        # weekly = request.get_data().decode("utf-8")
        # group_id=request.form.get('group')
        # print(group_id,weekly,type(weekly))
        data = sp.write_content(group_id, weekly)
        if data == "add succ":
            try:
                gen = generatePPTX(group_id)
                filename, defect = gen.generate_one()
            except Exception as e:
                ret = {"state": "0", "ms": str(e)}
                sp.update_status(group_id)
            else:
                ret = {"state": "1", "filename": filename}
        else:
            ret = {"state": "0", "ms": data}
        print(ret)
        return jsonify(ret)
    else:
        weekly = {"state": "0", "ms": "请使用post提交"}
        # weekly = {"state":"0", "ms":"小辉辉好"}
        return jsonify(weekly)


# 生成技术中心周报
@app.route('/generate_all', methods=['post'])
def generate_all():
    if request.method == 'POST':
        try:
            gen = generatePPTX(0)
            filename, defect = gen.generate_one()
        except Exception as e:
            ret = {"state": "0", "ms": str(e)}
        else:
            if defect == []:
                ret = {"state": "1", "filename": filename, "defect": defect}
            else:
                ret = {"state": "2", "filename": filename, "defect": defect}
        return jsonify(ret)


@app.route('/download_pptx/<filename>', methods=['get'])
def download_pptx(filename):
    print(filename)
    if request.method == "GET":
        way = "ppt/pptx/"
        file_dir = os.path.join(way, filename)
        print(way, filename)
        if os.path.isfile(file_dir):
            return send_from_directory(way, filename, as_attachment=True)
        else:
            abort(404)


@app.route('/upimg', methods=['post'])
def upimg():
    r = {"state": "0", "ms": "失败"}
    if request.method == 'POST':
        f = play.imgUp(request.files['file'])
        r = {"state": "1", "ms": "成功", "imgname": f}

    return jsonify(r)



if __name__ == '__main__':
    app.run(debug='true',host='0.0.0.0', port=5000)
